<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 命名空间选择 -->
      <el-select v-model="listQuery.namespace" placeholder="选择命名空间" style="width: 200px;" class="filter-item" clearable @change="handleNamespaceChange">
        <el-option v-for="ns in namespaceList" :key="ns" :label="ns" :value="ns" />
      </el-select>

      <el-input v-model="listQuery.name" placeholder="Service名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

      <!-- 批量操作按钮 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="danger"
        icon="el-icon-delete"
        :disabled="selectedServices.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>

      <!-- 根据标签删除 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="warning"
        icon="el-icon-delete"
        @click="handleDeleteByLabelDialog"
      >
        按标签删除
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选列 -->
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="Service名称" width="150px" align="center">
        <template slot-scope="{row}">
          <el-link type="primary" @click="showServiceDetail(row)">{{ row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="命名空间" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.namespace }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="集群IP" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.clusterIP }}</span>
        </template>
      </el-table-column>
      <el-table-column label="外部IP" width="130px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.externalIP && row.externalIP.length > 0">
            {{ row.externalIP.join(', ') }}
          </span>
          <span v-else-if="row.type === 'LoadBalancer' && row.status && row.status.loadBalancer && row.status.loadBalancer.ingress">
            {{ getLoadBalancerIP(row) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="端口" min-width="180px">
        <template slot-scope="{row}">
          <div v-if="row.ports && row.ports.length">
            <div v-for="port in row.ports" :key="`${port.port}-${port.protocol}`">
              <span v-if="(row.type === 'NodePort' || row.type === 'LoadBalancer') && port.nodePort">
                {{ port.name ? `${port.name}: ` : '' }}{{ port.port }}:{{ port.targetPort }}/{{ port.protocol }} (NodePort: {{ port.nodePort }})
              </span>
              <span v-else>
                {{ port.name ? `${port.name}: ` : '' }}{{ port.port }}:{{ port.targetPort }}/{{ port.protocol }}
              </span>
            </div>
          </div>
          <span v-else>无端口</span>
        </template>
      </el-table-column>
      <el-table-column label="标签选择器" min-width="200px">
        <template slot-scope="{row}">
          <div v-if="row.selector && Object.keys(row.selector).length">
            <el-tag
              v-for="(value, key) in row.selector"
              :key="key"
              size="small"
              style="margin: 2px;"
            >
              {{ key }}={{ value }}
            </el-tag>
          </div>
          <span v-else>无标签选择器</span>
        </template>
      </el-table-column>
      <el-table-column label="Service Labels" min-width="200px">
        <template slot-scope="{row}">
          <div v-if="row.labels && Object.keys(row.labels).length">
            <el-tag
              v-for="(value, key) in row.labels"
              :key="key"
              size="small"
              type="info"
              style="margin: 2px;"
            >
              {{ key }}={{ value }}
            </el-tag>
          </div>
          <span v-else>无Labels</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="deleteService(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 批量操作提示 -->
    <div v-if="selectedServices.length > 0" class="selected-tip">
      已选择 {{ selectedServices.length }} 个服务
    </div>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- Service详情对话框 - 按照kubectl describe格式 -->
    <el-dialog title="Service详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="currentServiceDetail" class="service-detail-content">
        <!-- 基本信息 - 按照kubectl describe格式 -->
        <el-card class="detail-card" shadow="never">
          <div slot="header" class="card-header">
            <span class="card-title">基本信息</span>
          </div>
          <div class="describe-format">
            <div class="describe-item">
              <span class="describe-label">Name:</span>
              <span class="describe-value">{{ currentServiceDetail.name }}</span>
            </div>
            <div class="describe-item">
              <span class="describe-label">Namespace:</span>
              <span class="describe-value">{{ currentServiceDetail.namespace }}</span>
            </div>
            <div class="describe-item">
              <span class="describe-label">Labels:</span>
              <span class="describe-value">
                <span v-if="currentServiceDetail.labels && Object.keys(currentServiceDetail.labels).length">
                  <el-tag
                    v-for="(value, key) in currentServiceDetail.labels"
                    :key="`label-${key}`"
                    size="small"
                    type="info"
                    style="margin: 2px;"
                  >
                    {{ key }}={{ value }}
                  </el-tag>
                </span>
                <span v-else class="none-text">&lt;none&gt;</span>
              </span>
            </div>
            <div class="describe-item">
              <span class="describe-label">Annotations:</span>
              <span class="describe-value">
                <span v-if="currentServiceDetail.annotations && Object.keys(currentServiceDetail.annotations).length">
                  <el-tag
                    v-for="(value, key) in currentServiceDetail.annotations"
                    :key="`annotation-${key}`"
                    size="small"
                    style="margin: 2px;"
                  >
                    {{ key }}={{ value }}
                  </el-tag>
                </span>
                <span v-else class="none-text">&lt;none&gt;</span>
              </span>
            </div>
            <div class="describe-item">
              <span class="describe-label">Selector:</span>
              <span class="describe-value">
                <span v-if="currentServiceDetail.selector && Object.keys(currentServiceDetail.selector).length">
                  <el-tag
                    v-for="(value, key) in currentServiceDetail.selector"
                    :key="`selector-${key}`"
                    size="small"
                    style="margin: 2px;"
                  >
                    {{ key }}={{ value }}
                  </el-tag>
                </span>
                <span v-else class="none-text">&lt;none&gt;</span>
              </span>
            </div>
            <div class="describe-item">
              <span class="describe-label">Type:</span>
              <span class="describe-value">{{ currentServiceDetail.type }}</span>
            </div>
            <div class="describe-item">
              <span class="describe-label">IP Family Policy:</span>
              <span class="describe-value">{{ getIPFamilyPolicy(currentServiceDetail) }}</span>
            </div>
            <div class="describe-item">
              <span class="describe-label">IP Families:</span>
              <span class="describe-value">{{ getIPFamilies(currentServiceDetail) }}</span>
            </div>
            <div class="describe-item">
              <span class="describe-label">IP:</span>
              <span class="describe-value">{{ currentServiceDetail.ip || '-' }}</span>
            </div>
            <div class="describe-item">
              <span class="describe-label">IPs:</span>
              <span class="describe-value">
                <span v-if="currentServiceDetail.ips && currentServiceDetail.ips.length">
                  {{ currentServiceDetail.ips.join(', ') }}
                </span>
                <span v-else class="none-text">&lt;none&gt;</span>
              </span>
            </div>
          </div>
        </el-card>

        <!-- 端口信息 -->
        <el-card class="detail-card" shadow="never">
          <div slot="header" class="card-header">
            <span class="card-title">端口信息</span>
          </div>
          <div class="ports-section">
            <div v-for="(port, index) in currentServiceDetail.ports" :key="index" class="port-row">
              <div class="describe-item">
                <span class="describe-label">Port:</span>
                <span class="describe-value">
                  {{ port.port }}  {{ port.port }}/{{ port.protocol }}
                </span>
              </div>
              <div class="describe-item">
                <span class="describe-label">TargetPort:</span>
                <span class="describe-value">
                  {{ formatTargetPort(port.targetPort) }}/{{ port.protocol }}
                </span>
              </div>
              <div v-if="port.nodePort" class="describe-item">
                <span class="describe-label">NodePort:</span>
                <span class="describe-value">
                  {{ port.nodePort }}  {{ port.nodePort }}/{{ port.protocol }}
                </span>
              </div>
            </div>
            <div v-if="!currentServiceDetail.ports || currentServiceDetail.ports.length === 0" class="describe-item">
              <span class="describe-label">Port:</span>
              <span class="describe-value none-text">&lt;none&gt;</span>
            </div>
          </div>
        </el-card>

        <!-- 端点信息 -->
        <el-card class="detail-card" shadow="never">
          <div slot="header" class="card-header">
            <span class="card-title">端点信息</span>
          </div>
          <div class="describe-format">
            <div class="describe-item">
              <span class="describe-label">Endpoints:</span>
              <span class="describe-value">
                <span v-if="currentServiceDetail.endpoints && currentServiceDetail.endpoints.subsets && currentServiceDetail.endpoints.subsets.length > 0">
                  {{ formatEndpoints(currentServiceDetail.endpoints) }}
                </span>
                <span v-else class="none-text">&lt;none&gt;</span>
              </span>
            </div>
            <div class="describe-item">
              <span class="describe-label">Session Affinity:</span>
              <span class="describe-value">{{ currentServiceDetail.sessionAffinity || 'None' }}</span>
            </div>
            <div class="describe-item">
              <span class="describe-label">External Traffic Policy:</span>
              <span class="describe-value">{{ currentServiceDetail.externalTrafficPolicy || 'Cluster' }}</span>
            </div>
          </div>
        </el-card>

        <!-- 事件信息 -->
        <el-card class="detail-card" shadow="never">
          <div slot="header" class="card-header">
            <span class="card-title">事件信息</span>
          </div>
          <div class="describe-format">
            <div class="describe-item">
              <span class="describe-label">Events:</span>
              <span class="describe-value">
                <span v-if="currentServiceDetail.events && currentServiceDetail.events.length">
                  <div v-for="(event, index) in currentServiceDetail.events" :key="index" class="event-item">
                    {{ event.type }} {{ event.reason }}: {{ event.message }}
                  </div>
                </span>
                <span v-else class="none-text">&lt;none&gt;</span>
              </span>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else>
        <el-skeleton :rows="6" animated />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 创建/编辑 Service 对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="700px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 100%; margin-left:0;">
        <el-form-item label="命名空间" prop="namespace">
          <el-select v-model="temp.namespace" placeholder="请选择命名空间" style="width: 100%;">
            <el-option v-for="ns in namespaceList" :key="ns" :label="ns" :value="ns" />
          </el-select>
        </el-form-item>
        <el-form-item label="Service名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" placeholder="请选择类型" style="width: 100%;" @change="handleTypeChange">
            <el-option label="ClusterIP" value="ClusterIP" />
            <el-option label="NodePort" value="NodePort" />
            <el-option label="LoadBalancer" value="LoadBalancer" />
          </el-select>
        </el-form-item>

        <!-- Service Labels -->
        <el-form-item label="Service Labels">
          <div class="labels-section">
            <div v-if="!temp.labels || temp.labels.length === 0">
              <el-button type="text" icon="el-icon-plus" @click="initLabels">添加Labels</el-button>
            </div>
            <div v-else>
              <div v-for="(label, index) in temp.labels" :key="`label-${index}`" class="label-item">
                <el-input v-model="label.key" placeholder="键" style="width: 180px;" />
                <span style="margin: 0 5px;">=</span>
                <el-input v-model="label.value" placeholder="值" style="width: 180px;" />
                <el-button
                  type="text"
                  style="margin-left: 10px;"
                  icon="el-icon-delete"
                  @click="removeLabel(index)"
                />
              </div>
              <el-button type="text" icon="el-icon-plus" @click="addLabel">添加Label</el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 端口配置 -->
        <el-form-item label="端口配置" prop="ports">
          <div v-for="(port, index) in temp.ports" :key="`port-${index}`" class="port-item">
            <el-input
              v-model="port.name"
              placeholder="端口名称"
              style="width: 120px;"
              :required="temp.ports.length > 1"
            />
            <el-input v-model.number="port.port" placeholder="端口" style="width: 80px;" type="number" />
            <span style="margin: 0 5px;">:</span>
            <el-input v-model.number="port.targetPort" placeholder="目标端口" style="width: 80px;" type="number" />
            <el-select v-model="port.protocol" placeholder="协议" style="width: 100px; margin-left: 5px;">
              <el-option label="TCP" value="TCP" />
              <el-option label="UDP" value="UDP" />
            </el-select>
            <!-- NodePort和LoadBalancer类型都显示NodePort输入框 -->
            <el-input
              v-if="temp.type === 'NodePort' || temp.type === 'LoadBalancer'"
              v-model.number="port.nodePort"
              placeholder="NodePort"
              style="width: 100px; margin-left: 5px;"
              type="number"
            />
            <el-button type="text" style="margin-left: 10px;" icon="el-icon-delete" @click="removePort(index)" />
          </div>
          <el-button type="text" icon="el-icon-plus" @click="addPort">添加端口</el-button>
        </el-form-item>
        <el-form-item label="标签选择器" prop="selectorLabels">
          <div v-for="(selector, index) in temp.selectorLabels" :key="`selector-${index}`" class="selector-item">
            <el-input v-model="selector.key" placeholder="键" style="width: 180px;" />
            <span style="margin: 0 5px;">=</span>
            <el-input v-model="selector.value" placeholder="值" style="width: 180px;" />
            <el-button
              type="text"
              style="margin-left: 10px;"
              icon="el-icon-delete"
              @click="removeSelectorLabel(index)"
            />
          </div>
          <el-button type="text" icon="el-icon-plus" @click="addSelectorLabel">添加标签选择器</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 根据标签删除对话框 -->
    <el-dialog title="根据标签删除Service" :visible.sync="deleteByLabelDialogVisible" width="500px">
      <el-form :model="deleteByLabelForm" label-position="left" label-width="120px">
        <el-form-item label="标签选择器" prop="labelSelector">
          <el-input
            v-model="deleteByLabelForm.labelSelector"
            placeholder="例如: app=nginx, version=1.0"
            type="textarea"
            :rows="3"
          />
          <div class="form-tips">
            <p><strong>标签选择器语法示例：</strong></p>
            <ul>
              <li><code>app=nginx</code> - 匹配标签 app=nginx</li>
              <li><code>app in (nginx, apache)</code> - 匹配 app 为 nginx 或 apache</li>
              <li><code>app=nginx,version=1.0</code> - 同时匹配 app=nginx 和 version=1.0</li>
              <li><code>app</code> - 存在 app 标签（值任意）</li>
              <li><code>!app</code> - 不存在 app 标签</li>
            </ul>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteByLabelDialogVisible = false">
          取消
        </el-button>
        <el-button type="warning" @click="deleteServicesByLabel">
          确认删除
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getServiceList,
  createService,
  deleteService,
  updateService,
  deleteMultipleServices,
  deleteServicesByLabel,
  getServiceDetail
} from '@/api/k8sService'
import { getNameSpaceList } from '@/api/k8sNamespace'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: 'ServiceTable',
  components: { Pagination },
  directives: { waves },

  data() {
    // 自定义端口验证规则
    const validatePorts = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('至少需要配置一个端口'))
        return
      }

      // 检查端口名称（当端口数量大于1时，每个端口名称必填）
      if (value.length > 1) {
        for (let i = 0; i < value.length; i++) {
          const port = value[i]
          if (!port.name || port.name.trim() === '') {
            callback(new Error(`端口 #${i + 1} 的名称是必填项（当有多个端口时）`))
            return
          }
        }
      }

      // 检查端口号是否重复
      const portNumbers = value.map(p => p.port).filter(p => p !== '')
      const uniquePorts = [...new Set(portNumbers)]
      if (portNumbers.length !== uniquePorts.length) {
        callback(new Error('端口号不能重复'))
        return
      }

      // 检查端口号是否有效
      for (let i = 0; i < value.length; i++) {
        const port = value[i]
        if (!port.port || port.port <= 0 || port.port > 65535) {
          callback(new Error(`端口 #${i + 1} 的端口号必须是1-65535之间的数字`))
          return
        }
        if (!port.targetPort || port.targetPort <= 0 || port.targetPort > 65535) {
          callback(new Error(`端口 #${i + 1} 的目标端口必须是1-65535之间的数字`))
          return
        }
        if (port.nodePort && (port.nodePort < 30000 || port.nodePort > 32767)) {
          callback(new Error(`端口 #${i + 1} 的NodePort必须是30000-32767之间的数字`))
          return
        }
      }

      callback()
    }

    return {
      tableKey: 0,
      list: [],
      namespaceList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        namespace: 'default',
        name: undefined,
        sort: '+id'
      },
      temp: {
        namespace: '',
        name: '',
        type: 'ClusterIP',
        labels: [],
        selectorLabels: [
          { key: '', value: '' }
        ],
        ports: [{ name: '', port: '', targetPort: '', protocol: 'TCP', nodePort: '' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑Service',
        create: '创建Service'
      },
      selectedServices: [],
      deleteByLabelDialogVisible: false,
      deleteByLabelForm: {
        labelSelector: ''
      },
      // 详情相关数据
      detailDialogVisible: false,
      currentServiceDetail: null,
      rules: {
        namespace: [{ required: true, message: '命名空间是必填项', trigger: 'change' }],
        name: [{ required: true, message: 'Service名称是必填项', trigger: 'blur' }],
        type: [{ required: true, message: '类型是必填项', trigger: 'change' }],
        ports: [{ validator: validatePorts, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getNamespaceList()
  },
  methods: {
    getNamespaceList() {
      getNameSpaceList().then(response => {
        console.log('命名空间列表响应:', response)
        if (response && response.nameSpaceList) {
          this.namespaceList = response.nameSpaceList.map(ns => ns.name)
        } else if (response && response.data) {
          this.namespaceList = response.data.map(ns => ns.name)
        }
        if (this.listQuery.namespace) {
          this.getList()
        }
      }).catch(error => {
        console.error('获取命名空间列表失败:', error)
        this.listLoading = false
      })
    },
    getList() {
      if (!this.listQuery.namespace) {
        this.listLoading = false
        this.list = []
        this.total = 0
        return
      }

      this.listLoading = true
      console.log('获取Service列表参数:', this.listQuery)

      getServiceList(this.listQuery.namespace, this.listQuery).then(response => {
        console.log('Service列表响应:', response)

        let serviceList = []

        // 处理不同的响应格式
        if (response && response.services) {
          serviceList = response.services
        } else if (response && response.data && response.data.services) {
          serviceList = response.data.services
        } else if (Array.isArray(response)) {
          serviceList = response
        } else {
          serviceList = []
        }

        console.log('处理后的Service列表:', serviceList)

        this.list = serviceList
        this.total = this.list.length

        // 延迟关闭loading，让用户体验更好
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      }).catch(error => {
        console.error('获取Service列表失败:', error)
        this.listLoading = false
        this.$message.error('获取Service列表失败: ' + (error.message || '未知错误'))
      })
    },
    handleNamespaceChange() {
      this.listQuery.page = 1
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 显示Service详情
    showServiceDetail(row) {
      this.detailDialogVisible = true
      this.currentServiceDetail = null

      getServiceDetail(row.namespace, row.name).then(response => {
        console.log('Service详情响应:', response)
        if (response.code === 20000) {
          this.currentServiceDetail = response
        } else {
          this.$message.error('获取Service详情失败: ' + response.message)
        }
      }).catch(error => {
        console.error('获取Service详情失败:', error)
        this.$message.error('获取Service详情失败')
      })
    },
    // 辅助方法
    getServiceTypeTag(type) {
      const typeMap = {
        'ClusterIP': 'primary',
        'NodePort': 'success',
        'LoadBalancer': 'warning'
      }
      return typeMap[type] || 'info'
    },
    getExternalIP(service) {
      // 优先使用externalIPs
      if (service.externalIP && service.externalIP.length > 0) {
        return service.externalIP.join(', ')
      }
      // 对于LoadBalancer类型，使用status.loadBalancer.ingress
      if (service.type === 'LoadBalancer' && service.status && service.status.loadBalancer && service.status.loadBalancer.ingress) {
        return service.status.loadBalancer.ingress.map(ingress => ingress.ip || ingress.hostname).join(', ')
      }
      return null
    },
    getLoadBalancerIP(row) {
      if (row.status && row.status.loadBalancer && row.status.loadBalancer.ingress) {
        return row.status.loadBalancer.ingress.map(ingress => ingress.ip || ingress.hostname).join(', ')
      }
      return '-'
    },
    hasNodePort(service) {
      return service.type === 'NodePort' || service.type === 'LoadBalancer'
    },
    // 新增的辅助方法
    getIPFamilyPolicy(service) {
      // 这里需要根据实际数据结构调整
      return service.ipFamilyPolicy || 'SingleStack'
    },
    getIPFamilies(service) {
      // 这里需要根据实际数据结构调整
      if (service.ipFamilies && service.ipFamilies.length > 0) {
        return service.ipFamilies.join(', ')
      }
      return 'IPv4'
    },
    formatTargetPort(targetPort) {
      if (!targetPort) return '-'
      // 如果targetPort是对象，可能需要特殊处理
      if (typeof targetPort === 'object') {
        return targetPort.value || targetPort.number || '-'
      }
      return targetPort
    },
    formatEndpoints(endpoints) {
      if (!endpoints || !endpoints.subsets || endpoints.subsets.length === 0) {
        return '<none>'
      }

      const result = []
      endpoints.subsets.forEach(subset => {
        if (subset.addresses && subset.addresses.length > 0) {
          subset.addresses.forEach(address => {
            if (subset.ports && subset.ports.length > 0) {
              subset.ports.forEach(port => {
                result.push(`${address.ip}:${port.port}`)
              })
            } else {
              result.push(address.ip)
            }
          })
        }
      })

      return result.length > 0 ? result.join(', ') : '<none>'
    },
    // 修改类型变更处理
    handleTypeChange(newType) {
      // 当类型改变为NodePort或LoadBalancer时，处理端口的nodePort字段
      if (newType === 'NodePort' || newType === 'LoadBalancer') {
        const newPorts = this.temp.ports.map(port => ({
          ...port,
          nodePort: port.nodePort || ''
        }))
        this.$set(this.temp, 'ports', newPorts)
      } else {
        // 如果是ClusterIP，移除nodePort字段
        const newPorts = this.temp.ports.map(port => {
          const { nodePort, ...rest } = port
          return rest
        })
        this.$set(this.temp, 'ports', newPorts)
      }
    },
    // 其他现有方法保持不变
    handleSelectionChange(selection) {
      this.selectedServices = selection
    },
    handleBatchDelete() {
      if (this.selectedServices.length === 0) {
        this.$message.warning('请先选择要删除的服务')
        return
      }

      const serviceNames = this.selectedServices.map(service => service.name)
      this.$confirm(`确定要删除选中的 ${serviceNames.length} 个Service吗？`, '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteMultipleServices(this.listQuery.namespace, { services: serviceNames })
          .then(response => {
            this.listLoading = false
            if (response.code === 20000) {
              if (response.data && response.data.failed && response.data.failed.length > 0) {
                this.$message.warning(`部分服务删除成功，失败的服务: ${response.data.failed.join(', ')}`)
              } else {
                this.$message.success('批量删除成功')
              }
              this.selectedServices = []
              this.getList()
            } else {
              this.$message.error('批量删除失败: ' + response.message)
            }
          })
          .catch(error => {
            this.listLoading = false
            console.error('批量删除Service失败:', error)
            this.$message.error('批量删除Service失败')
          })
      }).catch(() => {
        this.$message.info('已取消批量删除')
      })
    },
    handleDeleteByLabelDialog() {
      this.deleteByLabelForm.labelSelector = ''
      this.deleteByLabelDialogVisible = true
    },
    deleteServicesByLabel() {
      if (!this.deleteByLabelForm.labelSelector.trim()) {
        this.$message.error('请输入标签选择器')
        return
      }

      this.$confirm(`确定要根据标签选择器 "${this.deleteByLabelForm.labelSelector}" 删除Service吗？`, '按标签删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteServicesByLabel(this.listQuery.namespace, this.deleteByLabelForm.labelSelector.trim())
          .then(response => {
            this.listLoading = false
            this.deleteByLabelDialogVisible = false
            if (response.code === 20000) {
              this.$message.success(`根据标签删除成功，共删除 ${response.data.total} 个服务`)
              this.getList()
            } else {
              this.$message.error('根据标签删除失败: ' + response.message)
            }
          })
          .catch(error => {
            this.listLoading = false
            this.deleteByLabelDialogVisible = false
            console.error('根据标签删除Service失败:', error)
            this.$message.error('根据标签删除Service失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    resetTemp() {
      this.$set(this, 'temp', {
        namespace: this.listQuery.namespace || '',
        name: '',
        type: 'ClusterIP',
        labels: [],
        selectorLabels: [
          { key: '', value: '' }
        ],
        ports: [{ name: '', port: '', targetPort: '', protocol: 'TCP', nodePort: '' }]
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      const tempData = JSON.parse(JSON.stringify(row))

      if (tempData.selector && typeof tempData.selector === 'object') {
        tempData.selectorLabels = Object.keys(tempData.selector).map(key => ({
          key: key,
          value: tempData.selector[key]
        }))
      } else {
        tempData.selectorLabels = [{ key: '', value: '' }]
      }

      if (tempData.labels && typeof tempData.labels === 'object') {
        tempData.labels = Object.keys(tempData.labels).map(key => ({
          key: key,
          value: tempData.labels[key]
        }))
      } else {
        tempData.labels = []
      }

      tempData.ports = tempData.ports.map(port => {
        const portConfig = {
          name: port.name || '',
          port: port.port,
          targetPort: port.targetPort,
          protocol: port.protocol
        }

        if (tempData.type === 'NodePort' || tempData.type === 'LoadBalancer') {
          portConfig.nodePort = port.nodePort || ''
        }

        return portConfig
      })

      this.$set(this, 'temp', tempData)

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    initLabels() {
      this.$set(this.temp, 'labels', [{ key: '', value: '' }])
    },
    addLabel() {
      this.$set(this.temp.labels, this.temp.labels.length, { key: '', value: '' })
    },
    removeLabel(index) {
      if (this.temp.labels.length > 1) {
        this.temp.labels.splice(index, 1)
        this.$forceUpdate()
      } else {
        this.temp.labels = []
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const validLabels = this.temp.selectorLabels.filter(label => label.key && label.value)
          if (validLabels.length === 0) {
            this.$message.error('至少需要设置一个标签键值对')
            return
          }

          const selector = {}
          validLabels.forEach(label => {
            selector[label.key] = label.value
          })

          const labels = {}
          if (this.temp.labels && this.temp.labels.length > 0) {
            const validServiceLabels = this.temp.labels.filter(label => label.key && label.value)
            validServiceLabels.forEach(label => {
              labels[label.key] = label.value
            })
          }

          const ports = this.temp.ports.map(port => {
            const portConfig = {
              port: Number(port.port),
              targetPort: Number(port.targetPort),
              protocol: port.protocol
            }

            if (port.name && port.name.trim() !== '') {
              portConfig.name = port.name.trim()
            }

            if ((this.temp.type === 'NodePort' || this.temp.type === 'LoadBalancer') && port.nodePort) {
              portConfig.nodePort = Number(port.nodePort)
            }

            return portConfig
          })

          const requestData = {
            labels: Object.keys(labels).length > 0 ? labels : undefined,
            selector: selector,
            type: this.temp.type,
            ports: ports
          }

          console.log('发送到后端的数据:', JSON.stringify(requestData, null, 2))

          createService(this.temp.namespace, this.temp.name, requestData)
            .then((response) => {
              console.log('创建响应:', response)
              this.dialogFormVisible = false
              this.$notify.success('创建成功')
              this.getList()
            })
            .catch(error => {
              console.error('创建Service失败:', error)
              console.error('错误详情:', error.response?.data)
              this.$notify.error('创建Service失败: ' + (error.response?.data?.message || error.message))
            })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const validLabels = this.temp.selectorLabels.filter(label => label.key && label.value)
          if (validLabels.length === 0) {
            this.$message.error('至少需要设置一个标签键值对')
            return
          }

          const selector = {}
          validLabels.forEach(label => {
            selector[label.key] = label.value
          })

          const labels = {}
          if (this.temp.labels && this.temp.labels.length > 0) {
            const validServiceLabels = this.temp.labels.filter(label => label.key && label.value)
            validServiceLabels.forEach(label => {
              labels[label.key] = label.value
            })
          }

          const ports = this.temp.ports.map(port => {
            const portConfig = {
              port: Number(port.port),
              targetPort: Number(port.targetPort),
              protocol: port.protocol
            }

            if (port.name && port.name.trim() !== '') {
              portConfig.name = port.name.trim()
            }

            if ((this.temp.type === 'NodePort' || this.temp.type === 'LoadBalancer') && port.nodePort) {
              portConfig.nodePort = Number(port.nodePort)
            }

            return portConfig
          })

          const requestData = {
            labels: Object.keys(labels).length > 0 ? labels : undefined,
            selector: selector,
            type: this.temp.type,
            ports: ports
          }

          updateService(this.temp.namespace, this.temp.name, requestData)
            .then(() => {
              this.dialogFormVisible = false
              this.$notify.success('更新成功')
              this.getList()
            })
            .catch(error => {
              console.error('更新Service失败:', error)
              this.$notify.error('更新Service失败: ' + (error.response?.data?.message || error.message))
            })
        }
      })
    },
    deleteService(row) {
      this.$confirm(`确定要删除Service "${row.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteService(row.namespace, row.name).then(() => {
          this.getList()
          this.$message.success(`Service ${row.name} 删除成功`)
        }).catch(error => {
          console.error('删除Service失败:', error)
          this.listLoading = false
          this.$message.error('删除Service失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    addPort() {
      this.$set(this.temp.ports, this.temp.ports.length, {
        name: '',
        port: '',
        targetPort: '',
        protocol: 'TCP',
        nodePort: (this.temp.type === 'NodePort' || this.temp.type === 'LoadBalancer') ? '' : undefined
      })
    },
    removePort(index) {
      if (this.temp.ports.length > 1) {
        this.temp.ports.splice(index, 1)
        this.$forceUpdate()
      } else {
        this.$message.warning('至少保留一个端口配置')
      }
    },
    addSelectorLabel() {
      this.$set(this.temp.selectorLabels, this.temp.selectorLabels.length, { key: '', value: '' })
    },
    removeSelectorLabel(index) {
      if (this.temp.selectorLabels.length > 1) {
        this.temp.selectorLabels.splice(index, 1)
        this.$forceUpdate()
      } else {
        this.$message.warning('至少保留一个标签')
      }
    },
    formatTime(timestamp) {
      if (!timestamp) return ''
      try {
        return new Date(timestamp).toLocaleString()
      } catch (e) {
        return timestamp
      }
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    }
  }
}
</script>

<style scoped>
.port-item, .label-item, .selector-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.selected-tip {
  margin: 10px 0;
  padding: 10px;
  background-color: #f0f9ff;
  border: 1px solid #bee5eb;
  border-radius: 4px;
  color: #0c5460;
}

.form-tips {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 12px;
}

.form-tips ul {
  margin: 5px 0;
  padding-left: 20px;
}

.form-tips code {
  background-color: #e9ecef;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.labels-section {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
  background-color: #fafafa;
}

/* 详情页面样式 - kubectl describe格式 */
.service-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
  border: 1px solid #e6e6e6;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.describe-format {
  padding: 15px 20px;
}

.describe-item {
  display: flex;
  margin-bottom: 8px;
  line-height: 1.5;
}

.describe-label {
  width: 180px;
  font-weight: 500;
  color: #606266;
  flex-shrink: 0;
}

.describe-value {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

.none-text {
  color: #909399;
  font-style: italic;
}

.ports-section {
  padding: 15px 20px;
}

.port-row {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fafafa;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.event-item {
  margin-bottom: 5px;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 3px;
  font-family: monospace;
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .describe-item {
    flex-direction: column;
  }

  .describe-label {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>
